package com.ruoyi.system.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IEmployeeService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DynamicOrderExcelUtil;
import com.ruoyi.system.domain.DynamicOrderImportUtil;
import com.ruoyi.system.domain.MealOrder;
import com.ruoyi.system.domain.MealOrderVO;
import com.ruoyi.system.domain.vo.MealStatisticsBO;
import com.ruoyi.system.service.IMealOrderService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;

/**
 * 订餐管理Controller
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@RestController
@RequestMapping("/mealorder/order")
public class MealOrderController extends BaseController {
    @Autowired
    private IMealOrderService mealOrderService;

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 查询订餐管理列表
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(MealOrder mealOrder) {
        startPage();
        List<MealOrder> list = mealOrderService.selectMealOrderList(mealOrder);
        return getDataTable(list);
    }
    /**
     * 查询订餐管理VO列表
     */
    /**
     * 查询订餐管理VO列表
     */
    /**
     * 查询订餐管理VO列表
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:list')")
    @GetMapping("/voList")
    public TableDataInfo voList(MealOrderVO mealOrderVO,
                                @RequestParam(value = "emplyeeId", required = false) Long emplyeeId,
                                @RequestParam(value = "trainingId", required = false) Long trainingId) {
        // 手动设置emplyeeId属性，解决参数绑定问题
        if (emplyeeId != null) {
            mealOrderVO.setEmpId(emplyeeId);
        }
        // 设置培训ID
        if (trainingId != null) {
            mealOrderVO.setTrainingId(trainingId);
        }
        startPage();
        List<MealOrderVO> list = mealOrderService.selectMealOrderVOList(mealOrderVO);
        return getDataTable(list);
    }

    /**
     * 导出订餐管理列表
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:export')")
    @Log(title = "订餐管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export") // ✅ 改为 GET 请求
    public void export(HttpServletResponse response, MealOrderVO mealOrderVO) {
        try {
            Map<String, List<MealOrderExportVO>> groupedData = mealOrderService.selectGroupedExportData(mealOrderVO);
            MealOrderExportUtil.exportGroupedExcel(response, groupedData, "订餐管理数据.xlsx");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入订餐数据
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        // 使用新的动态导入工具
        List<MealOrder> mealOrderList = DynamicOrderImportUtil.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mealOrderService.importMealOrder(mealOrderList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 生成一个默认的导入模板（可以根据需要修改日期范围）
        Calendar cal = Calendar.getInstance();
        Date startDate = cal.getTime();
        cal.add(Calendar.DAY_OF_MONTH, 5); // 默认6天培训
        Date endDate = cal.getTime();

        DynamicOrderExcelUtil.generateOrderTemplate(
                response,
                "培训示例",
                startDate,
                endDate,
                "订餐导入模板"
        );
    }

    /**
     * 获取订餐管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(mealOrderService.selectMealOrderById(id));
    }

    /**
     * 新增订餐管理
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:add')")
    @Log(title = "订餐管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MealOrder mealOrder) {
        // 验证必要字段
        if (mealOrder.getTrainingId() == null) {
            return AjaxResult.error("培训ID不能为空");
        }

        if (mealOrder.getEmpId() == null) {
            // 如果没有员工ID，需要根据员工信息创建员工记录
            return AjaxResult.error("员工ID不能为空");
        }

        // 如果是新增，需要先检查员工是否存在，不存在则创建
        return toAjax(mealOrderService.insertMealOrder(mealOrder));
    }

    /**
     * 修改订餐管理
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:edit')")
    @Log(title = "订餐管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MealOrder mealOrder) {
        logger.info("接收到订餐更新请求: id={}, empId={}, trainingId={}, mealDetailsSize={}",
                mealOrder.getId(), mealOrder.getEmpId(), mealOrder.getTrainingId(),
                mealOrder.getMealDetails() != null ? mealOrder.getMealDetails().size() : 0);

        try {
            // 验证必要字段
            if (mealOrder.getEmpId() == null || mealOrder.getTrainingId() == null) {
                logger.error("更新订餐信息失败：empId或trainingId为空");
                return AjaxResult.error("员工ID和培训ID不能为空");
            }

            int result = mealOrderService.updateOrder(mealOrder);
            logger.info("订餐更新完成，影响记录数: {}", result);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            logger.error("订餐更新失败", e);
            return AjaxResult.error("修改失败: " + e.getMessage());
        }
    }

    /**
     * 删除订餐管理
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:remove')")
    @Log(title = "订餐管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(mealOrderService.deleteMealOrderByIds(ids));
    }

    /**
     * 查询培训订餐人数
     */
    @GetMapping("/orderCount")
    public AjaxResult getOrderCount(
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) Integer month,
            @RequestParam(required = false) Integer day,
            @RequestParam(defaultValue = "午餐") String mealType) {
        try {
            // 获取当前日期
            LocalDate now = LocalDate.now();

            // 如果所有日期参数都为空，则默认使用当年当月
            if (year == null && month == null && day == null) {
                year = now.getYear();
                month = now.getMonthValue();
            }

            // 参数校验
            if (year == null) {
                return AjaxResult.error("年份参数不能为空");
            }

            // 当月参数为空但日参数不为空时，报错
            if (month == null && day != null) {
                return AjaxResult.error("当月参数为空时，日参数必须为空");
            }

            // 必须提供月份参数
            if (month == null) {
                return AjaxResult.error("必须提供月份参数");
            }

            List<MealStatisticsBO> result = mealOrderService.getMealStatistics(year, month, day, mealType);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取单次培训午、晚餐订餐情况
     */
    @GetMapping("/trainingOrder")
    public AjaxResult getTrainingOrder(
            @RequestParam String trainingName) {
        return mealOrderService.getTrainingOrder(trainingName);
    }

    /**
     * 根据员工ID和培训ID删除订餐信息
     */
    @PreAuthorize("@ss.hasPermi('mealorder:order:remove')")
    @Log(title = "订餐管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/emp/{empId}/training/{trainingId}")
    public AjaxResult removeByEmpAndTraining(@PathVariable Long empId, @PathVariable Long trainingId) {
        // 删除指定员工在指定培训中的所有订餐记录
        int result = mealOrderService.deleteMealDetailsByEmpIdAndTrainingId(empId, trainingId);
        return toAjax(result);
    }

    /**
     * 导入订餐表
     */
    @PostMapping("/importMealOrderTable")
    public AjaxResult importMealOrderTable(@RequestParam("file") MultipartFile file,
                                           @RequestParam String trainingName,
                                           @RequestParam String startDate,
                                           @RequestParam String endDate,
                                           @RequestParam boolean updateSupport) {
        try {
            ExcelUtil<MealOrderTable> util = new ExcelUtil<MealOrderTable>(MealOrderTable.class);
            List<MealOrderTable> orderList = util.importExcel(file.getInputStream());
            return mealOrderService.importMealOrderTable(orderList, trainingName, startDate, endDate, updateSupport);
        } catch (Exception e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
}